package service;

import entity.Score;
import entity.Student;

import java.util.*;

//统计分析类
public class ScoreAnalysis {
    //用Map数据结构存储成绩
    private final Map<String,Score> scoreMap;
    public ScoreAnalysis(Map<String,Score> scores){
        this.scoreMap = scores;
    }
    
    /*
    计算各门成绩平均值
     */
    public double averageChinese(){
        if(scoreMap.isEmpty()){
            return 0.0;
        }
        double sum = 0;
        for(Score score : scoreMap.values()){
            sum+= score.getChinese();
        }
        return sum/scoreMap.size();
    }

    public double averageMath(){
        if(scoreMap.isEmpty()){
            return 0.0;
        }
        double sum = 0;
        for(Score score : scoreMap.values()){
            sum+= score.getMath();
        }
        return sum/scoreMap.size();
    }

    public double averageEnglish(){
        if(scoreMap.isEmpty()){
            return 0.0;
        }
        double sum = 0;
        for(Score score : scoreMap.values()){
            sum+= score.getEnglish();
        }
        return sum/scoreMap.size();
    }
    
    /*
     * 计算总分平均值
     */
    public double averageTotal() {
        if(scoreMap.isEmpty()){
            return 0.0;
        }
        double sum = 0;
        for(Score score : scoreMap.values()){
            sum+= score.getTotalScore();
        }
        return sum/scoreMap.size();
    }
    
    /*
     * 计算平均分平均值
     */
    public double averageOverall() {
        if(scoreMap.isEmpty()){
            return 0.0;
        }
        double sum = 0;
        for(Score score : scoreMap.values()){
            sum+= score.getAverageScore();
        }
        return sum/scoreMap.size();
    }

    /*
    总分排名
     */
    public void printScoresRanking(StudentManager studentManager) {
        if (scoreMap.isEmpty()) {
            System.out.println("无成绩，无法排名");
            return;
        }
        List<Score> scoreList = new ArrayList<>(scoreMap.values());

        //按总分降序排列  Lambda表达式
        scoreList.sort((s1, s2) -> Double.compare(s2.getTotalScore(), s1.getTotalScore()));

        System.out.println("按总分排名");
        int rank = 1;
        for (Score score : scoreList) {
            Student student = studentManager.getStudentById(score.getStudentId());
            if (student != null) {
                System.out.printf("第%d名:%s,总分:%.2f\n", rank, student.getName(), score.getTotalScore());
                System.out.println("学生信息:" + student);
                System.out.println("成绩详情:" + score);
            } else {
                System.out.printf("第%d名:学号:%s(未找到该学生),总分:%.2f\n", rank,score.getStudentId(), score.getTotalScore());
            }
            System.out.println("------------------------------------------");
            rank++;
        }
    }
    
    /*
     * 获取排名列表
     */
    public List<Map<String, Object>> getRankingList(StudentManager studentManager) {
        List<Map<String, Object>> rankingList = new ArrayList<>();
        
        if (scoreMap.isEmpty()) {
            return rankingList;
        }
        
        List<Score> scoreList = new ArrayList<>(scoreMap.values());
        scoreList.sort((s1, s2) -> Double.compare(s2.getTotalScore(), s1.getTotalScore()));

        int rank = 1;
        for (Score score : scoreList) {
            Map<String, Object> rankingItem = new HashMap<>();
            Student student = studentManager.getStudentById(score.getStudentId());
            
            rankingItem.put("rank", rank++);
            rankingItem.put("studentId", score.getStudentId());
            rankingItem.put("studentName", student != null ? student.getName() : "未知");
            rankingItem.put("chinese", score.getChinese());
            rankingItem.put("math", score.getMath());
            rankingItem.put("english", score.getEnglish());
            rankingItem.put("totalScore", score.getTotalScore());
            rankingItem.put("averageScore", score.getAverageScore());
            rankingItem.put("gradeLevel", score.getGradeLevel());
            
            rankingList.add(rankingItem);
        }
        
        return rankingList;
    }

    /*
    成绩分布分析
     */
    public void analyzeScoreDistribution() {
        if (scoreMap.isEmpty()) {
            System.out.println("暂无成绩记录");
            return;
        }
        int excellent=0;//240-300
        int pass=0;//180-239
        int fail=0;//0-179

        for (Score score : scoreMap.values()) {
            if (score.getTotalScore() >= 240) {
                excellent++;
            }else if (score.getTotalScore() >= 180&&score.getTotalScore()<240) {
                pass++;
            }else if (score.getTotalScore() >= 0&&score.getTotalScore()<180) {
                fail++;
            }
        }
        System.out.println("成绩分布分析");
        System.out.println("优秀(240-300)"+excellent+"人");
        System.out.println("及格(180-240)"+pass+"人");
        System.out.println("不及格(0-180)"+fail+"人");
    }
    
    /**
     * 获取指定科目的成绩分布
     * @param subject 科目名称 (chinese, math, english)
     * @return 成绩分布 Map，键为等级（优秀、良好、中等、及格、不及格），值为人数
     */
    public Map<String, Integer> getScoreDistribution(String subject) {
        Map<String, Integer> distribution = new HashMap<>();
        distribution.put("优秀", 0);
        distribution.put("良好", 0);
        distribution.put("中等", 0);
        distribution.put("及格", 0);
        distribution.put("不及格", 0);
        
        if (scoreMap.isEmpty()) {
            return distribution;
        }
        
        for (Score score : scoreMap.values()) {
            double subjectScore;
            
            // 根据科目获取对应成绩
            switch (subject.toLowerCase()) {
                case "chinese":
                    subjectScore = score.getChinese();
                    break;
                case "math":
                    subjectScore = score.getMath();
                    break;
                case "english":
                    subjectScore = score.getEnglish();
                    break;
                default:
                    subjectScore = score.getTotalScore() / 3; // 默认使用平均分
            }
            
            // 根据分数确定等级
            if (subjectScore >= 90) {
                distribution.put("优秀", distribution.get("优秀") + 1);
            } else if (subjectScore >= 80) {
                distribution.put("良好", distribution.get("良好") + 1);
            } else if (subjectScore >= 70) {
                distribution.put("中等", distribution.get("中等") + 1);
            } else if (subjectScore >= 60) {
                distribution.put("及格", distribution.get("及格") + 1);
            } else {
                distribution.put("不及格", distribution.get("不及格") + 1);
            }
        }
        
        return distribution;
    }
    
    /**
     * 获取最高分学生信息
     */
    public Map<String, Object> getTopStudent(StudentManager studentManager) {
        Map<String, Object> topStudent = new HashMap<>();
        
        if (scoreMap.isEmpty()) {
            return topStudent;
        }
        
        Score topScore = null;
        for (Score score : scoreMap.values()) {
            if (topScore == null || score.getTotalScore() > topScore.getTotalScore()) {
                topScore = score;
            }
        }
        
        if (topScore != null) {
            Student student = studentManager.getStudentById(topScore.getStudentId());
            topStudent.put("student", student);
            topStudent.put("score", topScore);
            topStudent.put("totalScore", topScore.getTotalScore());
        }
        
        return topStudent;
    }
    
    /**
     * 获取各科目最高分
     */
    public Map<String, Double> getSubjectTopScores() {
        Map<String, Double> topScores = new HashMap<>();
        
        if (scoreMap.isEmpty()) {
            return topScores;
        }
        
        double maxChinese = 0, maxMath = 0, maxEnglish = 0;
        
        for (Score score : scoreMap.values()) {
            if (score.getChinese() > maxChinese) {
                maxChinese = score.getChinese();
            }
            if (score.getMath() > maxMath) {
                maxMath = score.getMath();
            }
            if (score.getEnglish() > maxEnglish) {
                maxEnglish = score.getEnglish();
            }
        }
        
        topScores.put("chinese", maxChinese);
        topScores.put("math", maxMath);
        topScores.put("english", maxEnglish);
        
        return topScores;
    }
}